
const api = require('../../utils/api');

Page({
  /**
   * 页面的初始数据
   */
  data: {
    sceneryList: null,
    foodList: null,
    activityList: null,
    livesList: null,
    routeList: null,
    pageSize: 9,
    pageNum: 1,
    showCulSection: false,
    showFesSection: true,
    routeId: 1,
    routedetail: null,
    audioUrls: null,
    audioList: null,
    hotShare: null,
  },
  

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    this.loadSceneryList();
    this.loadFoodList();
    this.loadActivityList();
    this.loadLivesList();
    this.loadRouteList();
    this.loadAudiosList();
    this.loadHotShare();
  },
  

     
//导航跳转
scrollToSection(e){
    const targetId = e.currentTarget.dataset.target;
      wx.pageScrollTo({
        selector: `#${targetId}`,
        duration: 300,
        offsetTop: 0
      });
  },
  
  // 跳转到社区页面（其他用户分享）
  goToCommunity() {
    console.log('尝试跳转到社区主页面');
    wx.navigateTo({
      url: '/pages/community/communityMain/communityMain',
      success: function() {
        console.log('社区页面跳转成功');
      },
      fail: function(err) {
        console.error('社区页面跳转失败:', err);
        wx.showToast({
          title: '跳转失败',
          icon: 'none'
        });
      }
    });
  },
  
  // 跳转到我的分享历史页面
  goToMyShare() {
    console.log('尝试跳转到我的分享页面');
    wx.navigateTo({
      url: '/pages/community/myShare/myShare',
      success: function() {
        console.log('我的分享页面跳转成功');
      },
      fail: function(err) {
        console.error('我的分享页面跳转失败:', err);
        wx.showToast({
          title: '跳转失败',
          icon: 'none'
        });
      }
    });
  },
  


//音频
// 加载音频列表
loadAudiosList(){
    api.audios.getAudiosListApi().then(res => {
        const audioData = res.records || res.list || res || [];
        // 先设置基础音频数据
        this.setData({
            audioList: audioData.map(item => ({
                ...item,
                isPlaying: false,
                currentTime: 0,
                duration: 0,
                progress: 0
            }))
        });
        // 然后初始化音频上下文
        this.initAudioContexts();
    }).catch(err => {
        console.error('加载音频失败:',err);
    });
},

// 初始化音频上下文
initAudioContexts() {
    const audioList = this.data.audioList.map((item, index) => {
        const audioCtx = wx.createInnerAudioContext();
        audioCtx.src = item.soundUrl;
        audioCtx.index = index;
        
        // 监听音频可以播放时获取时长
        audioCtx.onCanplay(() => {
            setTimeout(() => {
                if (audioCtx.duration) {
                    const fixedDuration = parseFloat(audioCtx.duration.toFixed(2));
                    const newAudioList = [...this.data.audioList];
                    newAudioList[index].duration = fixedDuration;
                    this.setData({ audioList: newAudioList });
                }
            }, 100);
        });
        
        // 监听播放进度更新
        audioCtx.onTimeUpdate(() => {
            const fixedCurrentTime = parseFloat(audioCtx.currentTime.toFixed(2));
            const newAudioList = [...this.data.audioList];
            newAudioList[index].currentTime = fixedCurrentTime;
            newAudioList[index].progress = fixedCurrentTime;
            this.setData({ audioList: newAudioList });
        });
        
        // 监听播放结束
        audioCtx.onEnded(() => {
            const newAudioList = [...this.data.audioList];
            newAudioList[index].isPlaying = false;
            newAudioList[index].currentTime = 0;
            newAudioList[index].progress = 0;
            this.setData({ audioList: newAudioList });
        });
        
        // 监听错误
        audioCtx.onError((error) => {
            console.error('音频播放错误:', error);
            const newAudioList = [...this.data.audioList];
            newAudioList[index].isPlaying = false;
            this.setData({ audioList: newAudioList });
        });
        
        return { ...item, audioCtx };
    });
    
    this.setData({ audioList });
},

// 切换播放/暂停
togglePlay(e) {
    const index = e.currentTarget.dataset.index;
    const newAudioList = [...this.data.audioList];
    const currentAudio = newAudioList[index];
    
    if (!currentAudio.audioCtx) return;
    
    if (currentAudio.isPlaying) {
        currentAudio.audioCtx.pause();
    } else {
        // 先暂停其他正在播放的音频
        newAudioList.forEach((item, i) => {
            if (item.isPlaying && i !== index && item.audioCtx) {
                item.audioCtx.pause();
                item.isPlaying = false;
            }
        });  
        // 播放当前音频
        currentAudio.audioCtx.play();
    }
    
    currentAudio.isPlaying = !currentAudio.isPlaying;
    this.setData({ audioList: newAudioList });
},

// 拖动进度条改变播放位置
changeProgress(e) {
    const index = e.currentTarget.dataset.index;
    const value = e.detail.value;
    const newAudioList = [...this.data.audioList];
    
    if (newAudioList[index] && newAudioList[index].audioCtx) {
        newAudioList[index].audioCtx.seek(value);
        newAudioList[index].currentTime = value;
        newAudioList[index].progress = value;
        this.setData({ audioList: newAudioList });
    }
},

// 格式化时间为 分:秒 格式
formatTime(seconds) {
    if (!seconds || isNaN(seconds)) {
        return "00:00.00";
    }
    
    const totalSeconds = Math.floor(seconds);
    const decimalPart = Math.floor((seconds - totalSeconds) * 100);
    
    const minute = Math.floor(totalSeconds / 60);
    const second = totalSeconds % 60;
    
    return `${
        minute.toString().padStart(2, '0')
    }:${
        second.toString().padStart(2, '0')
    }.${
        decimalPart.toString().padStart(2, '0')
    }`;
},

// 页面卸载时销毁音频上下文
onUnload() {
    this.data.audioList.forEach(item => {
        item.audioCtx.destroy();
    });
},



//路线
onRoutetageTap(e){
    const id = e.currentTarget.dataset.id;
    console.log(id);
    this.setData({
        routeId:id
    });
},
loadRouteList(){
    const routeid = this.data.routeId;
    console.log('首页的路线id:',routeid);
    api.route.getRouteListApi(routeid).then(res => {
        const data = res.records || res.list || res;
        this.setData({
            routedetail: data.scenes || data
        });
    }).catch(err => {
        console.error('加载路线失败：', err);
    });
},

//住宿
loadLivesList(){
    const {pageNum,pageSize} = this.data;
    api.lives.getLIvesLIstApi(pageNum, pageSize).then(res => {
        this.setData({
            livesList: res.records || res.list || res
        });
    }).catch(err => {
        console.error('加载住宿失败',err);
    });
},


//活动
loadActivityList(theme = 1){
    api.activity.getActivityList(theme).then(res => {
        this.setData({
            activityList: res.records || res.list || res
        })
    }).catch(err => {
        console.error('加载活动失败:',err);
    });
},


// 美食
/**
 * 加载美食列表数据
 * @method loadFoodList
 * @description 调用API获取美食列表数据并更新页面数据
 * @returns {void}
 */
loadFoodList(){
    api.food.getFoodList().then(res => {
        this.setData({
            foodList: res.records || res.list || res
        });
    }).catch(err => {
        console.error('加载美食失败:',err);
    });
},

//加载热门分享
loadHotShare(){
    api.community.getHotShares().then(res => {
        this.setData({
            hotShare: res.records || res.list || res
        });
    }).catch(err => {
        console.log('加载热门分享失败：',err);
    });
},



  //美景
  loadSceneryList() {
      const {pageNum, pageSize} = this.data;
      api.scenery.getSceneryList(pageNum,pageSize).then(res => {
          this.setData({
              sceneryList: res.records || res.list || res
          });
      }).catch(err => {
          console.error('加载美景失败',err);
      });
  },
//美景跳转
sceneGoToDetail(e){
    const id = e.currentTarget.dataset.id;
    console.log('点击的美景id是：',id);
    wx.navigateTo({
      url: `../scenery/scenery?id=${id}`
    });
},
//美食跳转
foodGoToDetail(e){
    const id = e.currentTarget.dataset.id;
    console.log('点击的美食ID是：', id);
    wx.navigateTo({
      url: `../food/food?id=${id}`,
    });
},
//活动跳转
activityGoToDeatail(e){
    const id = e.currentTarget.dataset.id;
    console.log('点击的活动id是：', id);
    wx.navigateTo({
      url: `../activity/activity?id=${id}`,
    });
},

//路线跳转
RoutegoToDetail(e){
    const id = e.currentTarget.dataset.id;
    console.log('点击要进入的路线是:',id);
    if(id == 0 ){
        wx.navigateTo({
          url: `/pages/culroute/culroute?id=${id}`,
        });
    }else{
        wx.navigateTo({
          url: `/pages/redroute/redroute?id=${id}`,
        });
    }  
},

//住宿跳转
livesGoToDeatail(e){
    const id = e.currentTarget.dataset.id;
    console.log('点击的住宿id是：',id);
    wx.navigateTo({
      url:`/pages/lives/lives?id=${id}`,
    })  
},

onCultageTap(){
    this.setData({
       showCulSection: false,
       showFesSection: true
    });
    this.loadActivityList(1);
},
onFestageTap(){
    this.setData({
        showCulSection:true,
        showFesSection:false
    });
    this.loadActivityList(2);
},
//收藏跳转
storyGoToDetail(){
    wx.navigateTo({
      url: '../story/story',
    })
},
/**
 * 跳转到音频收藏页面
 */
audioGoToDetail(){
    wx.navigateTo({
      url: '/pages/audioCollection/audioCollection',
    })
},












  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },


  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})